﻿using System;
using System.Collections.Generic;
using AvaloniaApplicationDemo.DTO;
using Modbus.Device;
using SqlSugar;

namespace AvaloniaApplicationDemo.Util;

public  static class DataBaseManager
{
    private static volatile SqlSugarClient _dbClient;
    private static readonly Object _lockObj = new();
    public static SqlSugarClient DbClient
    {
        get
        {
            if (_dbClient == null)
            {
                lock (_lockObj)
                {
                    if (_dbClient == null)
                    {
                        AppLogger.Error(new Exception("数据库连接未初始化"), "来自初始化DbClient的异常");
                        throw new Exception("数据库连接未初始化");
                    }
                }
            }

            return _dbClient;
        }
        private set => _dbClient = value;
    }
    public static void InitDbClient(string connectionString)
    { 
        if (string.IsNullOrWhiteSpace(connectionString))
            throw new ArgumentNullException(nameof(connectionString), "数据库连接字符串不能为空！");

        lock (_lockObj)
        {
            if (_dbClient != null)
            {
                AppLogger.Warning("数据库客户端已初始化，无需重复调用！");
                return;
            }

            var config = new ConnectionConfig
            {
                ConnectionString = connectionString,
                DbType = DbType.MySql,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
              
            };

            DbClient = new SqlSugarClient(config);
            InitTables();

            DbClient.Aop.OnError = ex =>
            {
              AppLogger.Error(ex, "数据库操作异常");
            };

            AppLogger.Information("DataBase Initialized Successfully！");
        }
    
    }
    /// <summary>
    /// 初始化表结构，如果表不存在则创建
    /// </summary>
    private static void InitTables()
    {
        // SqlSugar 的 CodeFirst 会自动检查表是否存在，不存在才会创建
        try
        {
            DbClient.CodeFirst.InitTables<ModbusReportModel>();
        }
        catch (Exception e)
        {
           AppLogger.Error(e, "数据库初始化异常");
        }     
        // 可以添加更多需要初始化的实体类
        // Db.CodeFirst.InitTables<OtherEntity>();
    }
    
    public static class ModbusReportRepository
    {
        /// <summary>
        /// 新增数据
        /// </summary>
        public static bool Add(ModbusReportModel model)
        {
            return DbClient.Insertable(model).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 根据ID删除
        /// </summary>
        public static bool DeleteById(int id)
        {
            return DbClient.Deleteable<ModbusReportModel>().Where(m => m.Id == id).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 更新数据
        /// </summary>
        public static bool Update(ModbusReportModel model)
        {
            return DbClient.Updateable(model).Where(m => m.Id == model.Id).ExecuteCommand() > 0;
        }

        /// <summary>
        /// 根据ID查询
        /// </summary>
        public static ModbusReportModel? GetById(int id)
        {
            return DbClient.Queryable<ModbusReportModel>().Where(m => m.Id == id).First();
        }

        /// <summary>
        /// 查询所有数据
        /// </summary>
        public static List<ModbusReportModel> GetAll()
        {
            return DbClient.Queryable<ModbusReportModel>().ToList();
        }
    }
    
}